/**
*      author: Y_Yao
*      created: 2025-01-18 10:49:39
**/

#include<bits/stdc++.h>

#define int LL
using namespace std;
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 1000 + 6;
char a[N][N];
int h,w;
pair<int,int> s,e;
bool vis[N][N][2];


struct node
{
    int x,y,f,step;
};

int bfs()
{
    queue<node> q;
    q.push({s.first,s.second,0,0});
    q.push({s.first,s.second,1,0});

    while(!q.empty())
    {
        auto t = q.front();
        q.pop();

        if(t.x == e.first && t.y == e.second)
        {
            return t.step;
        }

        for(int i = -1;i <= 1;i+=2)
        {
            auto newnode = t;
            if(t.f == 0)
            {
                newnode.x += i;
            }
            else if(t.f == 1)
            {
                newnode.y += i;
            }

            newnode.f = 1 - t.f;
            newnode.step = t.step + 1;

            if(newnode.x<1||newnode.x>h||newnode.y<1||newnode.y>w)
                continue;
            if(vis[newnode.x][newnode.y][newnode.f]||a[newnode.x][newnode.y] == '#')
                continue;
            vis[newnode.x][newnode.y][newnode.f] = true;
            q.push(newnode);
        }
    }
    return -1;
}

void solve()
{
    cin >> h >> w;
    for(int i = 1;i <= h;i++)
    {
        for(int j = 1;j <= w;j++)
        {
            cin >> a[i][j];
            if(a[i][j] == 'S')
            {
                s = {i,j};
            }
            else if(a[i][j] == 'G')
            {
                e = {i,j};
            }
        }
    }


    cout << bfs() << endl;;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}